package cn.psh.pet.service.impl;

import cn.psh.basic.service.IBaiduAiAuditService;
import cn.psh.basic.util.*;
import cn.psh.basic.util.exception.BusinessException;
import cn.psh.order.domain.OrderPetAcquisition;
import cn.psh.order.mapper.OrderPetAcquisitionMapper;
import cn.psh.org.domain.Employee;
import cn.psh.org.domain.Log;
import cn.psh.org.domain.Shop;
import cn.psh.org.mapper.EmployeeMapper;
import cn.psh.org.mapper.ShopMapper;
import cn.psh.pet.domain.Pet;
import cn.psh.pet.domain.SearchMasterMsg;
import cn.psh.pet.domain.SearchMasterMsgAuditLog;
import cn.psh.pet.mapper.PetMapper;
import cn.psh.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.psh.pet.mapper.SearchMasterMsgMapper;
import cn.psh.pet.query.SearchMasterMsgQuery;
import cn.psh.pet.service.ISearchMasterMsgService;
import cn.psh.basic.service.impl.BaseServiceImpl;
import cn.psh.user.domain.Logininfo;
import cn.psh.user.domain.User;
import cn.psh.user.mapper.UserMapper;
import lombok.Lombok;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pider
 * @since 2022-09-28
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;


    @Transactional
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {

//        先保存寻主消息
        Logininfo login = LoginContext.getLogin(request);
        User user = userMapper.queryByLogininfo(login.getId());
        searchMasterMsgMapper.save(searchMasterMsg);
//        拿到哪个用户发布的寻主消息
        searchMasterMsg.setUserId(user.getId());
//      百度Ai智能审核
        Boolean aBoolean = baiduAiAuditService.textAudit(searchMasterMsg.getTitle() + searchMasterMsg.getGender() + searchMasterMsg.getName());
        Boolean aBoolean1 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
//       审核成功
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        log.setMsgId(searchMasterMsg.getId());
        if(aBoolean && aBoolean1){
//            修改状态searchMasterMsg  为1==>审核通过待处理
            searchMasterMsg.setState(1);
            searchMasterMsg.setUserId(user.getId());
            searchMasterMsg.setNote("发布成功");
//            保存审核日志
            log.setState(1);
            log.setNote("发布成功");
//            保存审核日志
            searchMasterMsgAuditLogMapper.save(log);
//            审核通过分配给最近得店铺
            List<Shop> shops = shopMapper.queryAll();
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            if(nearestShop==null){
                //说明最近50没有店铺，放入寻主池,修改状态
                searchMasterMsg.setState(3);
            }else {
//                说明分配成功，给寻主消息设置店铺
                searchMasterMsg.setShopId(nearestShop.getId());
                Employee employee = employeeMapper.queryById(nearestShop.getAdminId());
//                SmsUtils.sendSmsMsg(employee.getPhone(), "你有新的订单，请去"+searchMasterMsg.getAddress()+"接回宠物!!!");
                System.out.println("你有新的订单，请去"+searchMasterMsg.getAddress()+"接回宠物!!!");
            }
            searchMasterMsgMapper.update(searchMasterMsg);
        }else {

//            保存审核日志t_search_master_msg_audit_log
            log.setState(0);//审核失败
            log.setNote("发布失败");
            searchMasterMsgAuditLogMapper.save(log);

            //删除寻主消息
            searchMasterMsgMapper.del(searchMasterMsg.getId());

//            SmsUtils.sendSmsMsg(user.getPhone(), "审核失败!请重新填写信息");
//            System.out.println("审核失败!请重新填写信息");
            return AjaxResult.OJBK().setSuccess(false).setMessage("寻主消息发布失败");
        }
        return new  AjaxResult();
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
//        用户查询就不用设置state，用户查询得只是自己得消息，所以只需要设置userid
        Logininfo login = LoginContext.getLogin(request);
        User user = userMapper.queryByLogininfo(login.getId());
        query.setUserId(user.getId());
        return super.queryData(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
//        管理员查询需要状态
        query.setState(1);
        Logininfo login = LoginContext.getLogin(request);
        Employee employee = employeeMapper.queryByLogininfo(login.getId());
//        根据shopid去区分是平台管理员还是店铺管理员，平台管理员shopid为空
        query.setShopId(employee.getShopId());
        return super.queryData(query);
    }

    @Override
    public PageList<SearchMasterMsg> pool(SearchMasterMsgQuery query, HttpServletRequest request) {
//        查询寻主池
        //        管理员查询需要状态
        query.setState(3);
        Logininfo login = LoginContext.getLogin(request);
        Employee employee = employeeMapper.queryByLogininfo(login.getId());
//        根据shopid去区分是平台管理员还是店铺管理员，平台管理员shopid为空
        query.setShopId(employee.getShopId());
        return super.queryData(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        //        查询完成得
        query.setState(2);
        Logininfo login = LoginContext.getLogin(request);
        Employee employee = employeeMapper.queryByLogininfo(login.getId());
//        根据shopid去区分是平台管理员还是店铺管理员，平台管理员shopid为空
        query.setShopId(employee.getShopId());
        return super.queryData(query);
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(Map<String, String> map) {
       long msgId = Long.parseLong(map.get("msgId"));
       long empId = Long.parseLong(map.get("handler"));
       String note = map.get("note");
//        校验当前订单是否在处理
        final OrderPetAcquisition order = orderPetAcquisitionMapper.queryById(msgId);
        if(order!=null && order.getState() == 0){
            throw new BusinessException("订单正在处理，请勿重复接单！");
        }
//        通过msgId生成宠物，录入到系统
        SearchMasterMsg msg =searchMasterMsgMapper.queryById(msgId);
        Pet pet = mag2Pet(msg);
        petMapper.save(pet);
//        生成收购订单
        OrderPetAcquisition orderTmp = buidrPetAcquistion(msg,pet,empId,note);
        orderPetAcquisitionMapper.save(orderTmp);
        System.out.println("你有新的订单，请及时处理，地址："+msg.getAddress());
    }

    private OrderPetAcquisition buidrPetAcquistion(SearchMasterMsg msg, Pet pet, long empId, String note) {
        return null;
    }

    private Pet mag2Pet(SearchMasterMsg msg) {
        final Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0l);
        pet.setShopId(msg.getShopId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }

}
